<template>
  <div class="appointment-management">
    <h2>预约管理</h2>

    <!-- 预约状态标签筛选 -->
    <div class="filter-section">
      <el-radio-group v-model="statusFilter" @change="handleFilterChange">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="pending">待确认</el-radio-button>
        <el-radio-button label="confirmed">已确认</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 预约列表 -->
    <div class="appointment-list" v-loading="loading">
      <el-empty v-if="filteredAppointments.length === 0" description="暂无预约记录" />
      
      <el-card v-for="appointment in filteredAppointments" 
        :key="appointment.appointmentId" 
        class="appointment-card"
      >
        <div class="appointment-header">
          <div class="doctor-info">
            <div class="doctor-details">
              <h3>{{ appointment.doctorName }}</h3>
            </div>
          </div>
          <el-tag :type="getStatusType(appointment.status)">
            {{ getStatusText(appointment.status) }}
          </el-tag>
        </div>

        <div class="appointment-content">
          <div class="time-info">
            <el-icon><Calendar /></el-icon>
            <span>预约时间：{{ getWeekday(appointment.weekday) }} {{ appointment.begTime }}-{{ appointment.endTime }}</span>
          </div>
          <div class="action-buttons">
            <template v-if="appointment.status === 3">
              <el-button
                type="success"
                link
                @click="handleAcceptCancel(appointment)"
              >
                确认取消
              </el-button>
              <el-button
                type="danger"
                link
                @click="handleRejectCancel(appointment)"
              >
                拒绝取消
              </el-button>
            </template>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Calendar } from '@element-plus/icons-vue'
import { 
  getUserAppointments,
  userAcceptCancel,
  userRejectCancel,
  Appointment 
} from '../../api/appointment'

const loading = ref(false)
const statusFilter = ref('all')
const appointments = ref<Appointment[]>([])

// 根据筛选条件过滤预约
const filteredAppointments = computed(() => {
  if (!appointments.value) return []
  if (statusFilter.value === 'all') return appointments.value
  return appointments.value.filter(appointment => {
    if (statusFilter.value === 'pending') {
      return [0, 3, 4].includes(appointment.status)  // 包含所有待处理状态
    }
    if (statusFilter.value === 'confirmed') {
      return [1, 2].includes(appointment.status)     // 包含已确认和已完成
    }
    return true
  })
})

// 获取状态标签类型
const getStatusType = (status: number) => {
  const typeMap = {
    0: 'success',
    1: 'info',
    2: 'success',
    3: 'danger',
    4: 'danger',
    5: 'info',
    6: 'success',
    7: 'success',
    8: 'info'
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '已完成'
    case 1: return '待确认'
    case 2: return '已确认'
    case 3: return '对方申请取消'
    case 4: return '申请取消中'
    case 5: return '取消成功'
    case 6: return '已确认'
    case 7: return '已确认'
    case 8: return '取消成功'
    default: return '未知状态'
  }
}

// 获取星期几
const getWeekday = (weekday: number) => {
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return weekdays[weekday % 7]
}

// 处理筛选变化
const handleFilterChange = () => {
  // 仅根据状态筛选即可
}

// 获取预约列表
const fetchAppointments = async () => {
  loading.value = true
  try {
    const userId = localStorage.getItem('userid')
    if (!userId) {
      ElMessage.error('获取用户信息失败')
      return
    }
    
    const res = await getUserAppointments(Number(userId))
    if (res.code === '200') {
      appointments.value = res.data || []
    } else {
      ElMessage.error(res.msg || '获取预约列表失败')
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败')
  } finally {
    loading.value = false
  }
}

// 同意取消预约
const handleAcceptCancel = async (appointment: Appointment) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个预约吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await userAcceptCancel(appointment.appointmentId)
    if (res.code === '200') {
      ElMessage.success('已确认取消预约')
      fetchAppointments()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 拒绝取消预约
const handleRejectCancel = async (appointment: Appointment) => {
  try {
    await ElMessageBox.confirm(
      '确定拒绝取消这个预约吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await userRejectCancel(appointment.appointmentId)
    if (res.code === '200') {
      ElMessage.success('已拒绝取消预约')
      fetchAppointments()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

onMounted(() => {
  fetchAppointments()
})
</script>

<style scoped>
.appointment-management {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #2c3e50;
}

.filter-section {
  margin-bottom: 20px;
}

.appointment-card {
  margin-bottom: 20px;
}

.appointment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.doctor-details h3 {
  margin: 0;
  font-size: 16px;
  color: #2c3e50;
}

.appointment-content {
  padding: 16px 0;
  border-top: 1px solid #EBEEF5;
}

.time-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-tag {
  font-weight: 500;
  padding: 4px 8px;
}

.el-tag--warning {
  background-color: #fdf6ec;
}

.el-tag--success {
  background-color: #f0f9eb;
}

.el-tag--danger {
  background-color: #fef0f0;
}

.el-tag--info {
  background-color: #f4f4f5;
}

.el-button--link {
  padding: 4px 8px;
  height: auto;
}
</style>